package com.qf.edu.dao.impl;

import com.qf.edu.dao.DrugsLimit;
import com.qf.edu.entity.Drugs;
import com.qf.edu.utils.DBUtils;
import com.qf.edu.utils.PageUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:DrugsLimit接口实现类
 * @datatime: 2022/6/7 16:10
 */
public class DrugsLimitImpl implements DrugsLimit {
    private QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());

    @Override
    public List<Drugs> drugsLimt(PageUtils pageUtils) {
        String sql = "select * from drugs limit ? , ?";
        try {
            List<Drugs> query = queryRunner.query(sql, new BeanListHandler<>(Drugs.class), (pageUtils.getCurrentIndex() - 1) * pageUtils.getPageSize(), pageUtils.getPageSize());
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getDrugsAll() {
        String sql = "SELECT COUNT(*) FROM drugs";
        try {
            // 返回的是long类型  exception
            Object query = queryRunner.query(sql, new ScalarHandler<>());
            //query需要转int类型
            int count = Integer.parseInt(query.toString());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
